package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.event.LoginRecordEvent;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.system.domain.CommonConfig;
import com.ruoyi.system.domain.SysLoginRecord;
import com.ruoyi.system.domain.bo.SysLoginRecordBo;
import com.ruoyi.system.domain.vo.CommonConfigVo;
import com.ruoyi.system.domain.vo.LoginTimeVo;
import com.ruoyi.system.domain.vo.SysLoginRecordVo;
import com.ruoyi.system.mapper.CommonConfigMapper;
import com.ruoyi.system.mapper.SysLoginRecordMapper;
import com.ruoyi.system.service.ISysLoginRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统异常时间登录记录Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-30
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SysLoginRecordServiceImpl implements ISysLoginRecordService {

    private final SysLoginRecordMapper baseMapper;
    private final CommonConfigMapper commonConfigMapper;

    /**
     * 记录登录信息
     */
    @Async
    @EventListener
    public void abnormalLoginRecord(LoginRecordEvent recordEvent) {
        HttpServletRequest request = recordEvent.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = ServletUtils.getClientIP(request);
        String address = AddressUtils.getRealAddressByIP(ip);
        StringBuilder s = new StringBuilder();
        s.append(getBlock(ip));
        s.append(address);
        s.append(getBlock(recordEvent.getUsername()));
        s.append(getBlock(recordEvent.getStatus()));
        s.append(getBlock(recordEvent.getMessage()));
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();

        // 查询配置时间信息
        LambdaQueryWrapper<CommonConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonConfig::getType, "login_time");
        CommonConfigVo commonConfigVo = commonConfigMapper.selectVoOne(queryWrapper);
        if (commonConfigVo == null) {
            return;
        }
        LoginTimeVo loginTimeVo = JsonUtils.parseObject(commonConfigVo.getInfo(), LoginTimeVo.class);
        if (loginTimeVo == null) {
            return;
        }

        String startTime = loginTimeVo.getStartTime();
        String endTime = loginTimeVo.getEndTime();
        if (!StringUtils.isNotBlank(startTime) || !StringUtils.isNotBlank(endTime)) {
            return;
        }
        List<String> weekConfig = loginTimeVo.getWeekConfig();
        if (CollectionUtils.isEmpty(weekConfig)) {
            return;
        }
        // 获取当前日期是周几
        String week = DateUtils.getWeek();
        if (!StringUtils.isNotBlank(week)) {
            return;
        }
        if (!weekConfig.contains(week)) {
            return;
        }
        // 比较当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtils.HH_mm);
        String now = simpleDateFormat.format(new Date());
        try {
            Date nowTime = simpleDateFormat.parse(now);
            Date start = simpleDateFormat.parse(startTime);
            Date end = simpleDateFormat.parse(endTime);
            if (!DateUtils.isEffectiveDate(nowTime, start, end)) {
                // 记录登录信息
                SysLoginRecord logininfor = new SysLoginRecord();
                logininfor.setParentId(0L);
                logininfor.setAtTime(DateUtils.getDate());
                logininfor.setUserId(recordEvent.getUserId());
                logininfor.setUserName(recordEvent.getUsername());
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(recordEvent.getMessage());
                logininfor.setTimeRule(JsonUtils.toJsonString(loginTimeVo));
                // 日志状态
                if (StringUtils.equalsAny(recordEvent.getStatus(), Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(recordEvent.getStatus())) {
                    logininfor.setStatus(Constants.FAIL);
                }
                insertLoginRecord(logininfor);
            }
        } catch (Exception e) {
            log.info("异常登录报错：{}", e.getMessage());
        }
    }

    private String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }


    /**
     * 查询系统异常时间登录记录
     */
    @Override
    public SysLoginRecordVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询系统异常时间登录记录列表
     */
    @Override
    public TableDataInfo<SysLoginRecordVo> queryPageList(SysLoginRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysLoginRecord> lqw = buildQueryWrapper(bo);
        Page<SysLoginRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询系统异常时间登录记录列表
     */
    @Override
    public List<SysLoginRecordVo> queryList(SysLoginRecordBo bo) {
        LambdaQueryWrapper<SysLoginRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysLoginRecord> buildQueryWrapper(SysLoginRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysLoginRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, SysLoginRecord::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), SysLoginRecord::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getIpaddr()), SysLoginRecord::getIpaddr, bo.getIpaddr());
        lqw.eq(StringUtils.isNotBlank(bo.getLoginLocation()), SysLoginRecord::getLoginLocation, bo.getLoginLocation());
        lqw.eq(StringUtils.isNotBlank(bo.getBrowser()), SysLoginRecord::getBrowser, bo.getBrowser());
        lqw.eq(StringUtils.isNotBlank(bo.getOs()), SysLoginRecord::getOs, bo.getOs());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                SysLoginRecord::getLoginTime, params.get("beginTime"), params.get("endTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysLoginRecord::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getMsg()), SysLoginRecord::getMsg, bo.getMsg());
        lqw.eq(bo.getLoginTime() != null, SysLoginRecord::getLoginTime, bo.getLoginTime());
        lqw.eq(bo.getParentId() != null, SysLoginRecord::getParentId, bo.getParentId());
        lqw.eq(StringUtils.isNotBlank(bo.getTimeRule()), SysLoginRecord::getTimeRule, bo.getTimeRule());
        lqw.orderByDesc(SysLoginRecord::getLoginTime);
        return lqw;
    }

    /**
     * 新增系统异常时间登录记录
     */
    @Override
    public Boolean insertByBo(SysLoginRecordBo bo) {
        SysLoginRecord add = BeanUtil.toBean(bo, SysLoginRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改系统异常时间登录记录
     */
    @Override
    public Boolean updateByBo(SysLoginRecordBo bo) {
        SysLoginRecord update = BeanUtil.toBean(bo, SysLoginRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysLoginRecord entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除系统异常时间登录记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Long insertLoginRecord(SysLoginRecord bo) {
        bo.setLoginTime(new Date());
        int insert = baseMapper.insert(bo);
        return bo.getId();
    }


}
